import { Plugin } from '@nuxt/types';
import qs from 'qs';
import { Message } from 'element-ui';

declare module '@nuxt/types' {
    interface Context {
        $axios: any;
    }
}

declare module 'vue/types/vue' {
    interface Vue {
        $axios: any;
    }
}

declare module 'vuex/types/index' {
    interface Store<S> {
        $axios: any
    }
}

const myPlugin: Plugin = ({ app, $axios, store, redirect, error, route }) => {
    $axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    $axios.defaults.transformRequest = function (data: any) {
        return qs.stringify(data);
    };

    $axios.onRequest((config: { params: { guid?: any; token?: any; }; }) => {
        if (store && store.state && store.state.user) {
            const { guid, token } = store.state.user;

            if (!config.params) {
                config.params = {};
            }

            config.params.guid = guid;
            config.params.token = token;
        }
    })

    $axios.onResponse((res: any) => {
        // 返回code 5000 表示登陆过期
        let { code, msg } = res.data;
        let { fullPath } = route;
        if (code == 5005) { // 登陆已失效
            Message({
                type: 'error',
                message: msg
            });
            // 登陆失败清除记录
            store.dispatch('login', null);
            return redirect(`/?next=${fullPath}`);
        }
    });

    $axios.onError((err: any) => {
        console.log(err);
    });
}

export default myPlugin;
